﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace 餐饮管理系统
{
    public partial class MainWindow : Window
    {
        private void loadUserSelected()
        {
            //找到被选中的人的id
            ListBoxItem user = UserListBox.SelectedItem as ListBoxItem;
            if (user == null)
                return;
            string username = user.Content.ToString().Trim();
            //string id = staffInfo.Substring(0, staffInfo.IndexOf(":")).Trim();

            string sql = "select * from UserTable where name = '" + username + "'";
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            while (dataReader.Read())
            {
                UserIdTextBox.Text = dataReader[0].ToString().Trim();
                UserNameTextBox.Text = dataReader[1].ToString().Trim();
                UserPassword.Text = dataReader[2].ToString().Trim();
                UserPasswordCheck.Text = dataReader[2].ToString().Trim();
             
                if (dataReader[3] != null && !dataReader[3].ToString().Equals(""))
                {
                    UserPhoto.Source = DatabaseConnect.ByteArrayToBitmapImage(dataReader[3] as Byte[]);
                    UserAddPhotoButton.Opacity = 0;
                }
                else
                {
                    UserPhoto.Source = null;
                    UserAddPhotoButton.Opacity = 0.5;
                }
            }
            dataReader.Close();
        }

        private void loadUsers(int selectedIndex = 0)
        {
            string sql = "select name from UserTable";
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            UserListBox.Items.Clear();
            while (dataReader.Read())
            {
                string userName = dataReader[0].ToString().Trim();
                ListBoxItem item = new ListBoxItem();
                item.SetResourceReference(ListBoxItem.StyleProperty, "ListBoxItemStyle1");
                item.Content = userName;
                UserListBox.Items.Add(item);
            }
            dataReader.Close();

            if (selectedIndex < 0 || selectedIndex >= UserListBox.Items.Count)
                selectedIndex = 0;

            if (this.UserListBox.Items.Count > 0)
            {
                (this.UserListBox.Items[selectedIndex] as ListBoxItem).IsSelected = true;
                UserListBox.ScrollIntoView(UserListBox.Items[selectedIndex]);
            }
        }

        private void UserListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            loadUserSelected();
        }

        private int getUserNumber()
        {
            string sql = "select count(id) from UserTable";
            object buffer = databaseConnect.ExecuteScaler(sql);
            if (buffer == null)
            {
                return -1;
            }
            else
            {
                return (int)buffer;
            }
        }

        private void Zhuce_addButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string sql = "insert into UserTable(name) values('')";
            databaseConnect.ExecuteQuery(sql);
            loadUsers(getUserNumber() - 1);
        }


        private void UserDeleteButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string sql = "delete from usertable where id = "+UserIdTextBox.Text;
            databaseConnect.ExecuteQuery(sql);
            loadUsers(getUserNumber() - 1);
        }

        private void Zhuce_saveButton_Click(object sender, RoutedEventArgs e)
        {
            if (!UserPassword.Text.Equals(UserPasswordCheck.Text))
            {
                MessageBox.Show("两次密码输入不同！");
                return;
            }
            string sql = "update UserTable "
                       + "set name = '" + UserNameTextBox.Text + "',"
                       + "    password = '" + UserPassword.Text + "'"
                       + " where id = " + UserIdTextBox.Text;
            databaseConnect.ExecuteQuery(sql);

            try
            {
                if (UserPhoto.Source != null)
                {

                    FileStream fs = new FileStream(UserPhoto.Source.ToString().Substring(8), FileMode.Open, FileAccess.Read);
                    Byte[] imageByte = new Byte[fs.Length];
                    fs.Read(imageByte, 0, Convert.ToInt32(fs.Length));
                    fs.Close();
                    sql = "update UserTable set photo = @imgfile where id = " + UserIdTextBox.Text;
                    SqlParameter par = new SqlParameter("@imgfile", SqlDbType.Image);
                    par.Value = imageByte;
                    databaseConnect.ExecuteQuery(sql, par);
                }
            }
            catch (Exception)
            {
                //loadUsers(RenyuanListBox.SelectedIndex);
            }
            loadUsers(UserListBox.SelectedIndex);
        }

        private void UserAddPhotoButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Button addButton = sender as Button;
            addButton.ApplyTemplate();
            //Image userPhoto = addButton.Template.FindName("image", addButton) as Image;

            //创建＂打开文件＂对话框
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            //设置文件类型过滤
            dlg.Filter = "图片|*.jpg;*.png;*.gif;*.bmp;*.jpeg";

            // 调用ShowDialog方法显示＂打开文件＂对话框
            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                //获取所选文件名并在FileNameTextBox中显示完整路径
                string filename = dlg.FileName;

                //在image1中预览所选图片
                BitmapImage image = new BitmapImage(new Uri(filename));
                UserPhoto.Source = image;
                UserAddPhotoButton.Opacity = 0;
            }
        }
    }
}
